/** ************************************************************* **/
/**调用TIM通信云的JS文件,包含所用的调用TIM通信云WEB SDK tim-js示例**/
/** ************************************************************* **/
import Config from './config/config.js';
import Common from './common/common.js';
import Conversation from './model/conversation/Conversation.js' ;
import Menu from './model/menu/Menu.js';
import Group from './model/group/Group.js';
import Black from './model/blacklist/Black.js';
import Talk from './model/conversation/Talk.js';

const logger = Common.log("TimNet");
const options = {
    SDKAppID: Config.SDKAppID // 接入时需要将0替换为您的云通信应用的 SDKAppID
};
const tim = TIM.create(options); // SDK 实例通常用 tim 表示
tim.registerPlugin({'cos-js-sdk': COS}); // 在 login 前调用，以支持文件上传腾讯云对象存储
tim.setLogLevel(Config.LogLevel);

/*监听事件*/
//Sdk 的Ready状态。只有login 成功才会驱动 SDK 触发 SDK_READY 事件
let sdkReadyCallBack = null;
let sdkReadyStatus = false;
let onSdkReady = function (event) {
    if (sdkReadyCallBack) {
        sdkReadyCallBack(event)
     }
    sdkReadyStatus = true;
    //直接查询，SDK的监听，会刷新
    getGroupListFun();
    getBlacklistFun();
    logger.info("SDK_READY")
};
tim.on(TIM.EVENT.SDK_READY, onSdkReady);

//SDK 进入 not ready 状态时触发，此时接入侧将无法使用 SDK 发送消息等功能。
// 如果想恢复使用，接入侧需调用 login 接口，驱动 SDK 进入 ready 状态
let onSdkNotReady = function (event) {
    sdkReadyStatus = false;
    //重新弹出登陆框登录
    Menu.openLoginWin();
    Conversation.clear();
    Group.clear();
    Black.clear();
    Talk.close();
    Common.cache.myProfile = {};
    logger.info("SDK_NOT_READY")
};
tim.on(TIM.EVENT.SDK_NOT_READY, onSdkNotReady);

//收到会话刷新的监听
let onConversationListUpdated = function (event) {
    Conversation.setConversationListData(event.data)
};
tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, onConversationListUpdated);

//收到信息的监听
let onMessageReceived = function (event) {
    // event.data - 存储 Message 对象的数组 - [Message]
    logger.debug("收到消息", event.data);
    //添加消息
    for (let i = event.data.length - 1; i >= 0; i--) {
       Talk.messReceived(event.data[i]);
    }
};
tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);

//收到撤回信息的监听
let onMessageRevoked = function(event) {
    logger.debug("撤回信息", event.data);
    for (let i = event.data.length - 1; i >= 0; i--) {
      //  Talk.messRevoked(event.data[i]);
    }
};
tim.on(TIM.EVENT.MESSAGE_REVOKED, onMessageRevoked);

//SDK 群组列表更新时触发
let onGroupListUpdated = function(event) {
    if(sdkReadyStatus){
        Group.setGroupList(event.data);// 包含 Group 实例的数组
    }
};
tim.on(TIM.EVENT.GROUP_LIST_UPDATED, onGroupListUpdated);

//黑名单监听
let onBlacklistUpdated = function(event) {
    if(sdkReadyStatus){
        Black.setBlackUser(event.data);
    }
};
tim.on(TIM.EVENT.BLACKLIST_UPDATED, onBlacklistUpdated);

/*登录接口*/
let loginFun = function (userID, userSig, success) {
    //一些sdk,只有登录后改变ready状态才能使用
    sdkReadyCallBack = function (event) {
        if (success) {
            success();
        }
    };
    let promise = tim.login({userID: userID, userSig: userSig});
    promise.then(function (imResponse) {
        if (imResponse.data.repeatLogin === true) {
            // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
            logger.info(imResponse.data.errorInfo);
        }
    }).catch(function (imError) {
        logger.warn('login error:', imError); // 登录失败的相关信息
    });
};


/*获取用户信息*/
let getMyProfileFun = function (success) {
    //获取当前用户信息
    let promise = tim.getMyProfile();

    promise.then(function (imResponse) {
        //imResponse.data 个人资料 - Profile 实例
        if (success) {
            success(imResponse.data)
        }
    }).catch(function (imError) {
        logger.warn('getMyProfile error:', imError); // 获取个人资料失败的相关信息
    });
}

/*更新用户信息*/
/*
*  nick: '我的昵称',
*  avatar: 'http(s)://url/to/image.jpg',
*  gender: TIM.TYPES.GENDER_MALE,
*  selfSignature: '我的个性签名',
*  allowType: TIM.TYPES.ALLOW_TYPE_ALLOW_ANY
*/
let updateMyProfileFun = function (data,success) {
    let promise = tim.updateMyProfile(data);
    promise.then(function(imResponse) {
        if (success) {
            success(imResponse.data)
        }
    }).catch(function(imError) {
        logger.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
    });
}

/*获取指定用户信息*/
let getUserProfileFun = function (userIDList, success) {

    //拉起指定用户
    // 请注意：即使只拉取一个用户的资料，也需要用数组类型，例如：userIDList: ['user1']
    let promise = tim.getUserProfile({
        userIDList: userIDList
    });

    promise.then(function (imResponse) {
        //imResponse.data 个人资料 - Profile 实例
        if (success) {
            success(imResponse.data)
        }
    }).catch(function (imError) {
        logger.warn('getUserProfile error:', imError); // 获取个人资料失败的相关信息
    });
}

/*加入黑名单*/
let addToBlacklistFun = function(userIDList,success){
    let promise = tim.addToBlacklist({userIDList: userIDList}); // 请注意：即使只添加一个用户帐号到黑名单，也需要用数组类型，例如：userIDList: ['user1']
    promise.then(function(imResponse) {
        if (success) {
            success(imResponse.data)
        }
    }).catch(function(imError) {
        logger.warn('addToBlacklist error:', imError); // 添加用户到黑名单列表失败的相关信息
    });
}


/*获取会话列表*/
let getConversationListFun = function (success) {
    let promise = tim.getConversationList();
    promise.then(function (imResponse) {
        if (success) {
            success(imResponse.data.conversationList)
        }
        ; // 会话列表
    }).catch(function (imError) {
        logger.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
    });
}

/*删除会话列表*/
let deleteConversationFun = function (conversationID,success) {
    let promise = tim.deleteConversation(conversationID);
    promise.then(function(imResponse) {
        if (success) {
            success(imResponse.data);
        }
    }).catch(function(imError) {
        logger.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
    });
}

/*获取群主列表*/
let getGroupListFun = function (success) {
    let promise = tim.getGroupList();
    promise.then(function(imResponse) {
        if (success) {
            success(imResponse.data.groupList);
        }
     }).catch(function(imError) {
        logger.warn('getGroupList error:', imError); // 获取群组列表失败的相关信息
    });
}

/*获取黑名单列表*/
let getBlacklistFun = function (success) {
    let promise = tim.getBlacklist();
    promise.then(function(imResponse) {
        if (success) {
            success(imResponse.data);
        }
    }).catch(function(imError) {
        logger.warn('getBlacklist error:', imError); // 获取黑名单列表失败的相关信息
    });
}

/*移除黑名单列表*/
let removeFromBlacklistFun = function (userID,success) {
    let promise = tim.removeFromBlacklist({userIDList: [userID]}); // 请注意：即使只从黑名单中移除一个用户帐号，也需要用数组类型，例如：userIDList: ['user1']
    promise.then(function(imResponse) {
        if (success) {
            success(imResponse.data);
        }// 从黑名单中成功移除的账号列表，结构为包含用户 userID 的数组 - [userID]
    }).catch(function(imError) {
        logger.warn('removeFromBlacklist error:', imError); // 将用户从黑名单中移除失败的相关信息
    });
}



//发送信息
let sendMessageFun = function (message, success, error) {
    let promise = tim.sendMessage(message);
    promise.then(function (imResponse) {
        // 发送成功
        if (success) {
            success(imResponse)
        }
        ;
    }).catch(function (imError) {
        // 发送失败
        if (error) {
            error(imError)
        }
        logger.warn('sendMessage error:', imError);
    });
}


//发送文本信息
let sendTextMessageFun = function (text, conversationType, toID, success, error) {
    let message = tim.createTextMessage({
        to: toID,
        conversationType: conversationType,
        payload: {
            text: text
        }
    });
    sendMessageFun(message, success, error);
}

//发送表情信息
let sendFaceMessageFun = function (index,data, conversationType, toID, success, error) {
    let message = tim.createFaceMessage({
        to: toID,
        conversationType: conversationType,
        payload: {
            index: index, // Number 表情索引，用户自定义
            data: data// String 额外数据
        }
    });
    sendMessageFun(message, success, error);
}


//发送图片信息
let sendImageMessageFun = function (fileInput, conversationType, toID, success, error,progress) {
    let message = tim.createImageMessage({
        to: toID,
        conversationType: conversationType,
        payload: {
            file: fileInput,
        },
        onProgress: function(event) {
            if(progress){
                progress(event)
            }
         }
    });
    sendMessageFun(message, success, error);
}

//发送文件信息
let sendFileMessageFun = function (fileInput, conversationType, toID, success, error,progress) {
    let message = tim.createFileMessage({
        to: toID,
        conversationType: conversationType,
        payload: {
            file: fileInput,
        },
        onProgress: function(event) {
            if(progress){
                progress(event)
            }
        }
    });
    sendMessageFun(message, success, error);
}

//发送视频信息
let sendVideoMessageFun=function (fileInput, conversationType, toID, success, error,progress) {
    let message = tim.createVideoMessage({
        to: toID,
        conversationType: conversationType,
        payload: {
            file: fileInput,
        },
        onProgress: function(event) {
            if(progress){
                progress(event)
            }
        }
    });
    sendMessageFun(message, success, error);
}

// 主动撤回消息
let revokeMessageFun = function (message, success,error) {
    let promise = tim.revokeMessage(message);
    promise.then(function(imResponse) {
        if (success){success(imResponse);}
    }).catch(function(imError) {
        if (error){error(imError);}
    });
}


//获取会话的详细信息conversationID 由可以事userID/groupID/SYSTEM
let getConversationProfileFun = function (conversationID, success) {
    let promise = tim.getConversationProfile(conversationID);
    promise.then(function (imResponse) {
        // 获取成功
        if (success) {success(imResponse.data.conversation);}// 会话资料

    }).catch(function (imError) {
        logger.warn('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
    });
}

//获取会话消息列表
let getMessageListFun = function (conversationID, nextReqMessageID, success) {
    let promise;
    if (!nextReqMessageID) {
        promise = tim.getMessageList({conversationID: conversationID, count: 15});
    } else {
        promise = tim.getMessageList({conversationID: conversationID, nextReqMessageID, count: 15});
    }
    promise.then(function (imResponse) {
        //mResponse.data.messageList; // 消息列表。
        //imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
        //imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
        success(imResponse);
    });
}

// 将某会话下所有未读消息已读上报
let setMessageReadFun = function (conversationID, success) {
    let promise = tim.setMessageRead({conversationID: conversationID});
    promise.then(function(imResponse) {
        if (success) {success(imResponse);}
    }).catch(function(imError) {
        // 已读上报失败
        logger.warn('setMessageRead error:', imError);
    });
}

// 创建好友工作群，200人群
let createGroupFun = function (avatar,name,introduction,notification,joinOption,memberList, success) {
    let promise = tim.createGroup({
        type: TIM.TYPES.GRP_WORK,
        avatar:avatar,
        name:name,
        introduction: introduction,
        notification: notification,
        joinOption:joinOption,
        maxMemberCount:200,
        memberList: memberList // 如果填写了 memberList，则必须填写 userID
    });
    promise.then(function(imResponse) { // 创建成功
        if (success) {success(imResponse.data.group);}  // 创建的群的资料
    }).catch(function(imError) {
        logger.warn('createGroup error:', imError); // 创建群组失败的相关信息
    });
}

// 更新好友工作群
let updateGroupProfileFun = function (groupID,avatar,name,introduction,notification, success) {
    let promise = tim.updateGroupProfile({
        groupID:groupID,
        avatar:avatar,
        name:name,
        introduction: introduction,
        notification: notification
    });
    promise.then(function(imResponse) {
        if (success) {success(imResponse.data.group);}  // 创建的群的资料
    }).catch(function(imError) {
        logger.warn('updateGroupProfile error:', imError); // 修改群组资料失败的相关信息
    });
}


// 获取群详细资料
let getGroupProfileFun = function (groupID , success) {
    let promise = tim.getGroupProfile({
        groupID: groupID
    });
    promise.then(function(imResponse) {
        if (success) {success(imResponse.data.group);}
    }).catch(function(imError) {
        logger.warn('getGroupProfile error:', imError); // 获取群详细资料失败的相关信息
    });
}

// 获取群人员
let getGroupMemberListFun = function (groupID , success) {
    let promise = tim.getGroupMemberList(
        {
            groupID: groupID,
            count: 200,
            offset:0
        }); // 从0开始拉取200个群成员
    promise.then(function(imResponse) {
         if (success) {success(imResponse.data.memberList);}
    }).catch(function(imError) {
        logger.warn('getGroupMemberList error:', imError);
    });
}

// 移除群人员
let deleteGroupMemberFun = function (groupID ,userIDList, success) {
    let promise = tim.deleteGroupMember({
        groupID:groupID,
        userIDList:userIDList
     });
    promise.then(function(imResponse) {
        if (success) {success(imResponse.data);}
    }).catch(function(imError) {
        logger.warn('deleteGroupMember error:', imError); // 错误信息
    });
}


// 添加群人员
let addGroupMemberFun = function (groupID ,userIDList, success) {
    let promise = tim.addGroupMember({groupID:groupID, userIDList:userIDList});
    promise.then(function(imResponse) {
        if (success) {success(imResponse.data);}
    }).catch(function(imError) {
        logger.warn('addGroupMember error:', imError); // 错误信息
    });
}

//退群
let quitGroupFun = function (groupID , success) {
    let promise = tim.quitGroup(groupID);
    promise.then(function(imResponse) {
        if (success) {success(imResponse.data)}  // 退出成功的群 ID
    }).catch(function(imError){
        logger.warn('quitGroup error:', imError); // 退出群组失败的相关信息
    });
}



export default {
    /*登录TIM*/
    login: loginFun,
    /*获取用户信息*/
    getMyProfile:getMyProfileFun,
    /*更新用户信息*/
    updateMyProfile: updateMyProfileFun,
    /*获取指定用户信息*/
    getUserProfile:getUserProfileFun,
    /*加入到黑名单*/
    addToBlacklist: addToBlacklistFun,
    /*获取会话列表*/
    getConversationList: getConversationListFun,
    /*删除会话列表*/
    deleteConversation:deleteConversationFun,
    /*获取群主列表*/
    getGroupList:getGroupListFun,
    /*创建好友工作群*/
    createGroup:createGroupFun,
    /*更新好友工作群*/
    updateGroupProfile:updateGroupProfileFun,
    /*退出好友群*/
    quitGroup:quitGroupFun,
    /*获取群详细资料*/
    getGroupProfile:getGroupProfileFun,
    /*获取群人员*/
    getGroupMemberList:getGroupMemberListFun,
    /* 移除群人员*/
    deleteGroupMember:deleteGroupMemberFun,
    /* 添加群人员*/
    addGroupMember:addGroupMemberFun,
    /*获取黑名单列表*/
    getBlacklist:getBlacklistFun,
    /*移除黑名单列表*/
    removeFromBlacklist:removeFromBlacklistFun,
    /*获取会话内容*/
    getConversationProfile: getConversationProfileFun,
    /*获取会话消息列表*/
    getMessageList: getMessageListFun,
    /*发送文本信息*/
    sendTextMessage: sendTextMessageFun,
    /*发送表情信息*/
    sendFaceMessage:sendFaceMessageFun,
    /*发送图片信息*/
    sendImageMessage:sendImageMessageFun,
    /*发送文件信息*/
    sendFileMessage:sendFileMessageFun,
    /*发送视频信息*/
    sendVideoMessage:sendVideoMessageFun,
    /*撤回信息*/
    revokeMessage:revokeMessageFun,
    /*将某会话下所有未读消息已读上报*/
    setMessageRead:setMessageReadFun
}
